package com.renne.email.service.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.io.FileUtil;
import com.renne.common.exception.ServiceException;
import com.renne.email.domain.MailSenderConfigVo;
import com.renne.email.service.IMailSenderConfigService;
import com.renne.email.service.MailPushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.renne.common.utils.DateUtils;
import com.renne.common.utils.SecurityUtils;
import com.renne.common.core.domain.entity.SysUser;
import com.renne.common.core.domain.model.LoginUser;
import com.renne.common.utils.uuid.IdUtils;
import com.renne.common.utils.bean.BeanUtils;
import com.renne.common.core.text.Convert;
import com.renne.email.domain.MailItemQuery;
import com.renne.email.domain.MailItemVo;
import com.renne.email.domain.MailItem;
import com.renne.email.mapper.MailItemMapper;
import com.renne.email.service.IMailItemService;

import javax.mail.MessagingException;


/**
 * 邮件明细Service业务层处理
 *
 * @author LiuYu
 * @date 2024-07-26
 */
@Service
public class MailItemServiceImpl implements IMailItemService {
    private final Logger logger = LoggerFactory.getLogger(MailItemServiceImpl.class);

    @Autowired
    private IMailSenderConfigService mailSenderConfigService;

    @Autowired
    private MailItemMapper mailItemMapper;

    @Autowired
    private MailPushService mailPushService;

    /**
     * 查询邮件明细
     *
     * @param mailItemId 邮件明细ID
     * @return 邮件明细
     */
    @Override
    public MailItemVo getMailItemVoById(String mailItemId) {
        return mailItemMapper.selectMailItemVoById(mailItemId);
    }

    /**
     * 查询邮件明细列表
     *
     * @param query 邮件明细
     * @return 邮件明细集合
     */
    @Override
    public List<MailItemVo> getMailItemVoList(MailItemQuery query) {
        return mailItemMapper.selectMailItemVoList(query);
    }

    /**
     * 新增邮件明细
     *
     * @param mailItemVo 邮件明细Vo
     * @return 结果
     */
    @Override
    public int saveMailItemVo(MailItemVo mailItemVo) {
        MailItem mailItem = new MailItem();
        BeanUtils.copyBeanProp(mailItem, mailItemVo);
        mailItem.setMailItemId(IdUtils.fastSimpleUUID());
        mailItem.setStatus("2");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        mailItem.setDeptId(sysUser.getDeptId());
        mailItem.setCreateById(SecurityUtils.getUserId());
        mailItem.setCreateBy(SecurityUtils.getUsername());
        mailItem.setCreateTime(DateUtils.getNowDate());
        return mailItemMapper.insertMailItem(mailItem);

    }

    /**
     * 修改邮件明细
     *
     * @param mailItemVo 邮件明细Vo
     * @return 结果
     */
    @Override
    public int updateMailItemVo(MailItemVo mailItemVo) {
        MailItem mailItem = new MailItem();
        BeanUtils.copyBeanProp(mailItem, mailItemVo);
        mailItem.setUpdateBy(SecurityUtils.getUsername());
        mailItem.setUpdateTime(DateUtils.getNowDate());
        return mailItemMapper.updateMailItem(mailItem);
    }

    /**
     * 删除邮件明细对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteMailItemByIds(String ids) {
        return mailItemMapper.deleteMailItemByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除邮件明细信息
     *
     * @param mailItemId 邮件明细ID
     * @return 结果
     */
    @Override
    public int deleteMailItemById(String mailItemId) {
        return mailItemMapper.deleteMailItemById(mailItemId);
    }

    /**
     * 批量邮件发送
     *
     * @param list 邮件明细
     */
    @Override
    public void sendEmailByMailItem(List<MailItemVo> list) {
        MailSenderConfigVo config = mailSenderConfigService.getEnabledMailSenderConfigVo();
        if (config == null) {
            throw new ServiceException("请先配置发送邮件的邮箱");
        }
        for (MailItemVo mailItemVo : list) {
            try {
                sendEmail(mailItemVo);
                mailItemVo.setStatus("1");
            } catch (MessagingException | GeneralSecurityException | UnsupportedEncodingException e) {
                logger.error("邮件发送失败", e);
                mailItemVo.setStatus("0");
            }
            // 更新邮件发送状态
            int number = null == mailItemVo.getSendNumber() ? 1 : mailItemVo.getSendNumber() + 1;
            mailItemVo.setSendNumber(number);
            mailItemVo.setLastSendTime(DateUtils.getNowDate());
            mailItemVo.setSendEmail(config.getEmail());
            updateMailItemVo(mailItemVo);
        }
    }

    /**
     * 批量邮件发送
     *
     * @param mailItemIds 邮件明细IDs
     */
    @Override
    public void sendEmailByMailItemIds(String mailItemIds) {
        MailSenderConfigVo config = mailSenderConfigService.getEnabledMailSenderConfigVo();
        if (config == null) {
            throw new ServiceException("请先配置发送邮件的邮箱");
        }
        String[] mailItemIdArray = Convert.toStrArray(mailItemIds);
        for (String mailItemId : mailItemIdArray) {
            MailItemVo mailItemVo = getMailItemVoById(mailItemId);
            try {
                sendEmail(mailItemVo);
                mailItemVo.setStatus("1");
            } catch (MessagingException | GeneralSecurityException | UnsupportedEncodingException e) {
                logger.error("邮件发送失败", e);
                mailItemVo.setStatus("0");
            }
            // 更新邮件发送状态
            int number = null == mailItemVo.getSendNumber() ? 1 : mailItemVo.getSendNumber() + 1;
            mailItemVo.setSendNumber(number);
            mailItemVo.setLastSendTime(DateUtils.getNowDate());
            mailItemVo.setSendEmail(config.getEmail());
            updateMailItemVo(mailItemVo);
        }
    }

    /**
     * 邮件发送
     *
     * @param mailItemVo 邮件明细
     */
    private void sendEmail(MailItemVo mailItemVo) throws MessagingException, GeneralSecurityException, UnsupportedEncodingException {
        // 邮件附件
        String filePath = mailItemVo.getFilePath();
        boolean directory = FileUtil.isDirectory(filePath);
        File[] files = null;
        if (directory) {
            files = FileUtil.ls(filePath);
        } else {
            File file = FileUtil.file(filePath);
            // 转成数组
            files = new File[1];
            files[0] = file;
        }
        // 邮件发送
        mailPushService.sendMail(mailItemVo.getToEmail(), mailItemVo.getCopyEmail(), mailItemVo.getTitle(), mailItemVo.getContent(), Arrays.asList(files));
    }
}
